import { createRouter,createWebHistory } from "vue-router";

import HomeMain from "@/components/HomeMain";
import Login from "@/components/Login";
import axios from "axios";
import {ElNotification} from "element-plus";

const routes = [
    {
        path: '/',
        name: "logIn",
        redirect: '/login'
    },
    {
        path: '/login',
        name: "login",
        component: Login
    },
    {
        path: '/home',
        name: "HomeMain",
        component: HomeMain
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

router.beforeEach((to, from, next) => {
    // 判断有没有登录
    if (!localStorage.getItem('token')) { // 没有token
        if (to.name === "login" || to.name === "logIn") {  // 要进登录页面
            next();
        } else {   // 强制进登录界面
            router.push('login')
        }
    } else {  // 有token
        axios.post("/api/loginVerify", localStorage.getItem("token")).then(res=>{
            if (res.data.code === 200) {
                if (to.name === "login" || to.name === "logIn") {
                    ElNotification({
                        title: '成功',
                        message: res.data.msg,
                        type: 'success'
                    })
                    router.push("/home")
                } else {
                    next()
                }
            } else if (res.data.code === 210) {
                localStorage.setItem("token", res.data.data)
                ElNotification({
                    title: '成功',
                    message: res.data.msg,
                    type: 'success'
                })
                router.push("/home")
            } else {
                ElNotification({
                    title: '错误',
                    message: res.data.msg,
                    type: 'error'
                })
                localStorage.removeItem("token")
                router.push('login')
            }
        })
    }
});

export default router;